package com.smartstate.ems.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.smartstate.ems.dto.EnergyDTO;
import com.smartstate.ems.dto.PageDTO;
import com.smartstate.ems.entity.EnergyReport;
import com.smartstate.ems.mapper.EnergyReportMapper;
import com.smartstate.ems.service.EnergyReportService;
import com.smartstate.ems.vo.ResultVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/EnergyReport")
public class EnergyReportController {

    @Resource
    private EnergyReportService energyReportService;

    @Resource
    private EnergyReportMapper energyReportMapper;

//    能源日报导出
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出能源报表信息excel")
    public ResultVO exportExcel(HttpServletResponse response, @RequestBody EnergyDTO energyDTO) throws IOException {
        log.info("开始导出excel");
        //energyDTO.setAnalysisObject(energyReportMapper.queryRootObjId("空间结构建模"));
        List<EnergyReport> exportExcel = energyReportService.exportExcel(energyDTO);
        setExcelRespProp(response, "能耗报表");
        if (CollectionUtils.isEmpty(exportExcel) || exportExcel.size() <= 0){
            return ResultVO.fail("报表信息为空");
        }
        //获取项目数据
        List<List<String>> projectDataList = new ArrayList<>();
        projectDataList = inputProjectData(projectDataList, energyDTO, "表具电表统计");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            //新建sheet
            WriteSheet writeSheet = EasyExcel.writerSheet("能耗报表").build();
            //获取表格样式
            HorizontalCellStyleStrategy dataTableStrategy = cellStyle();
            //新建table
            WriteTable writeTable = EasyExcel.writerTable(0).needHead(false).registerWriteHandler(dataTableStrategy).build();
            WriteTable writeTable2 = EasyExcel.writerTable(1).head(EnergyReport.class).
                    registerWriteHandler(new SimpleColumnWidthStyleStrategy(25)).needHead(true).build();
            //往table里写数据
            excelWriter.write(projectDataList, writeSheet, writeTable);
            excelWriter.write(exportExcel, writeSheet, writeTable2);
            //关闭流
            excelWriter.finish();
            log.info("导出excel成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultVO.ok();
    }

    /**
     * 设置第一行样式
     * @return
     */
    public HorizontalCellStyleStrategy cellStyle (){
        // 1>创建第一行的样式
        WriteCellStyle firstRow = new WriteCellStyle();
        // 2>设置加粗，其他样式保持一致
        firstRow.setWriteFont(setFont(0, null, true));
        firstRow.setBorderLeft(BorderStyle.THIN);
        firstRow.setBorderRight(BorderStyle.THIN);
        firstRow.setBorderBottom(BorderStyle.THIN);
        //创建表格第一行外的其他内容样式
        WriteCellStyle bodyStyle = new WriteCellStyle();
        // 设置边框
        bodyStyle.setBorderLeft(BorderStyle.THIN);
        bodyStyle.setBorderRight(BorderStyle.THIN);
        bodyStyle.setBorderBottom(BorderStyle.THIN);
        // 3>根据总行数]，叠加生成最后一行的样式List
        List<WriteCellStyle> preList = new ArrayList<>();
        preList.add(firstRow);
        for (int i = 5; i > 0; i--){
            preList.add(bodyStyle);
        }
        return new HorizontalCellStyleStrategy(null, preList);
    }

    /**
     * 项目数据
     * @param projectDataList
     * @param energyDTO
     * @param reportContext
     * @return
     */
    private List<List<String>> inputProjectData(List<List<String>> projectDataList, EnergyDTO energyDTO, String reportContext) {
        List<String> arrayList1 = new ArrayList<>();
        arrayList1.add("项目数据");
        arrayList1.add("");
        projectDataList.add(arrayList1);
        List<String> arrayList2 = new ArrayList<>();
        arrayList2.add("报表名称");
        Map<String, Object> objectMap = energyReportMapper.queryAllObjId("1");
        Map<String, Object> map = (Map) objectMap.get(energyDTO.getAnalysisObject());
        String objIdName = "";
        while(true){
            objIdName = objIdName == "" ? map.get("name") + objIdName : map.get("name") + "-" + objIdName;
            if ("0".equals(map.get("parentId"))){
                break;
            }
            map = (Map) objectMap.get(map.get("parentId"));
        }
        objIdName = objIdName + "能耗报表";
        arrayList2.add(objIdName);
        projectDataList.add(arrayList2);
        List<String> arrayList3 = new ArrayList<>();
        arrayList3.add("数据时间");
        String dateTimeStr = null;
        if (energyDTO.getStartTime().equals(energyDTO.getEndTime())){
            dateTimeStr = energyDTO.getStartTime().replace("-", "/");
        }else {
            dateTimeStr = energyDTO.getStartTime().replace("-", "/") + " - " + energyDTO.getEndTime().replace("-", "/");
        }
        arrayList3.add(dateTimeStr);
        projectDataList.add(arrayList3);
        List<String> arrayList4 = new ArrayList<>();
        arrayList4.add("能耗单位");
        arrayList4.add("kW·h");
        projectDataList.add(arrayList4);
        List<String> arrayList5 = new ArrayList<>();
        arrayList5.add("报表内容");
        arrayList5.add(reportContext);
        projectDataList.add(arrayList5);
        List<String> arrayList6 = new ArrayList<>();
        arrayList6.add("导出时间");
        DateTime dateTime = new DateTime();
        String currentDateTimeStr = DateUtil.format(dateTime, "yyyy/MM/dd HH:mm:ss");
        arrayList6.add(currentDateTimeStr);
        projectDataList.add(arrayList6);
        projectDataList.add(new ArrayList<>());
        return projectDataList;
    }


    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    /**
     * @purpose 设置字体
     * @parameter size为0或name为null表示不设置字体
     */
    public static WriteFont setFont(int size, String name, boolean condition) {
        WriteFont font = new WriteFont();
        // 大小
        if (size > 0){
            font.setFontHeightInPoints((short) size);
        }
        // 字体
        if (!ObjectUtils.isEmpty(name)) {
            font.setFontName(name);
        }
        // 是否加粗
        font.setBold(condition);
        return font;
    }

    /**
     * 能耗日报查询
     * @param pageDTO
     * @return
     */
    @PostMapping("/queryEneryDay")
    public ResultVO queryEneryDay(@RequestBody PageDTO<EnergyDTO> pageDTO){
        return ResultVO.ok(energyReportService.queryEneryDay(pageDTO));
    }
}
